package com.example.administrator.demo02;

import android.app.Activity;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.ToggleButton;
import android.widget.VideoView;
import java.util.Random;
import master.flame.danmaku.controller.DrawHandler;
import master.flame.danmaku.danmaku.model.BaseDanmaku;
import master.flame.danmaku.danmaku.model.DanmakuTimer;
import master.flame.danmaku.danmaku.model.IDanmakus;
import master.flame.danmaku.danmaku.model.android.DanmakuContext;
import master.flame.danmaku.danmaku.model.android.Danmakus;
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser;
import master.flame.danmaku.ui.widget.DanmakuView;

public class MainActivity extends Activity {

    private boolean showDanmaku;
    private DanmakuView danmakuView;
    private DanmakuContext danmakuContext;

    private GestureDetector mGesture;
    //弹幕解析器（创建全局的解析器）
    private BaseDanmakuParser parser = new BaseDanmakuParser() {
        @Override
        protected IDanmakus parse() {
            return new Danmakus();
        }
    };
    //视频布局
    VideoView videoView;
    LinearLayout operationLayout;
    //输入弹幕
    EditText editText;
    //发送按钮
    Button send;
    //弹幕开关按钮
    Switch open_switchd;
    //进度条
    SeekBar seekBar;
//    ToggleButton toggleBtn;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        operationLayout = findViewById(R.id.operation_layout);
        editText = findViewById(R.id.edit_text);
        send = findViewById(R.id.send);
        open_switchd = findViewById(R.id.open_switchd);
//        toggleBtn = findViewById(R.id.toggleBtn);
        danmakuView = findViewById(R.id.danmaku_view);
        seekBar = findViewById(R.id.seebar);
        //声明了本地视屏文件的路径
        String videoUrl1 = "/sdcard/Movies/123.mkv";//INEEDU.mp4
        Uri uri = Uri.parse( videoUrl1 );
        videoView = findViewById(R.id.video_view);
        videoView.setVideoURI(uri);
        videoView.start();

        //调用了enableDanmakuDrawingCache()方法来提升效率
        danmakuView.enableDanmakuDrawingCache(true);
        //调用setCallback()方法设置回调函数
        danmakuView.setCallback(new DrawHandler.Callback() {
            @Override
            public void prepared() {
                showDanmaku=true;
                danmakuView.start();
//                generateSomeDanmaku();
            }

            @Override
            public void updateTimer(DanmakuTimer timer) {

            }

            @Override
            public void danmakuShown(BaseDanmaku danmaku) {

            }

            @Override
            public void drawingFinished() {

            }

        });

        danmakuContext = DanmakuContext.create();
        danmakuView.prepare(parser,danmakuContext);
        sendDanmaku();

        //当切换到横屏时接着播放
        if (savedInstanceState != null){
            //得到视频的播放进度
            int min = savedInstanceState.getInt("aa");
            //接着播放
            videoView.seekTo(min);
        }

    }

    /**
     *设置视频时间进度条
     */
    private void ProgressBar(){
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                //进度条进度改变的时候调用
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                //进度条开始拖动的时候调用
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                //进度条停止拖动的时候调用
                //取得当前进度条的刻度
                int progress = seekBar.getProgress();
                if (videoView != null && videoView.isPlaying()){
                    //设置当前播放的位置
                    videoView.seekTo(progress);
                }

            }
        });
    }

    /***
     * 向视屏中添加一条弹幕
     * @param context
     *        弹幕的具体内容
     * @param withBordert
     *        弹幕是否有边框
     */
    private void addDanmaku(String context,boolean withBordert){

        BaseDanmaku danmaku = danmakuContext.mDanmakuFactory.
                createDanmaku(BaseDanmaku.TYPE_SCROLL_RL);//TYPE_SCROLL_RL（弹幕的方向，这里是从右向左）
        danmaku.text = context;
        danmaku.padding = 5;
        danmaku.textSize = sp2px(20);
        danmaku.textColor = Color.WHITE;
        danmaku.setTime(danmakuView.getCurrentTime());
        //用于指定的弹幕是否带有边框以别与区分
        if (withBordert){
            danmaku.borderColor = Color.GREEN;
        }
        danmakuView.addDanmaku(danmaku);
    }

    /**
     * 随机生成一些弹幕测试
     */
    private void generateSomeDanmaku(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (showDanmaku){
                    int time = new Random().nextInt(300);
                    String content = "" +time + time;
                    addDanmaku(content,false);
                    try {
                        Thread.sleep(time);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    /**
     * sp转px的方法
     *
     */
    public int sp2px(float spValue){
        final float fontScale = getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }



    @Override
    protected void onPause() {
        super.onPause();
        if (danmakuView != null && danmakuView.isPrepared()){
            danmakuView.pause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (danmakuView != null && danmakuView.isPrepared() && danmakuView.isPaused()){
            danmakuView.resume();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        showDanmaku = false;
        if (danmakuView !=null){
            danmakuView.release();
            danmakuView = null;
        }
    }


    private void sendDanmaku(){
        /**
         * 给danmakuView设置点击事件，如果当前界面是不是操作界面，
         *     点击将操作界面显示出来，反之则隐藏，这样便可以通过点击屏幕来实现操作界面的隐藏和显示
         * 给videoview设置点击事件，如果当前视频是播放状态，点击暂停，反之则播放
         *  PS:操作界面是发送弹幕的布局
         */
        danmakuView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (operationLayout.getVisibility() == View.GONE && videoView.isPlaying()){
                    operationLayout.setVisibility(View.VISIBLE);
                    videoView.pause();
                }else {
                    operationLayout.setVisibility(View.GONE);
                    videoView.start();
                }
            }
        });
        /**
         * 为发送按钮设置点击事件
         *  再点击发送后，获取到输入框中的内容然后调用addDanmaku()方法将这条消息添加到DanmakuView上
         *  这条弹幕是由我们自己发送的，因此addDanmaku()方法的第二个参数要传入true。
         */
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = editText.getText().toString();
                if (!TextUtils.isEmpty(content)){
                    addDanmaku(content,true);
                    editText.setText("");
                }
            }
        });
        /**
         * 由于系统输入法弹出的时候会导致焦点丢失，从而退出沉浸式模式，因此这里对系统全局的UI变化做了
         * 监听，保证程序一直处于沉浸式模式
         */
        getWindow().getDecorView().setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
            @Override
            public void onSystemUiVisibilityChange(int visibility) {
                if (visibility == View.SYSTEM_UI_FLAG_VISIBLE){
                    onWindowFocusChanged(true);
                }
            }
        });
        //控制是否开启弹幕
        open_switchd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked){
                    generateSomeDanmaku();
                }else{

                }
            }
        });
        ProgressBar();
//        toggleBtn.toggle();
//        toggleBtn.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                return false;
//            }
//        });
    }

    /**
     * 使用沉浸式，使视屏播放时全屏 （隐藏顶部导航栏和底部导航栏）
     * @param hasFocus
     */
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus && Build.VERSION.SDK_INT >=19){
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }
    }

    //重新定义onSaveInstanceState()，用于切换横竖屏之后，视频不会重新播放，
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("aa",videoView.getCurrentPosition());
    }


}
